package com.nwpu.bigdata.cronJob;

import com.nwpu.bigdata.dto.BackendResult;
import com.nwpu.bigdata.exception.NoLogExcetion;
import com.nwpu.bigdata.model.FaultKey;
import com.nwpu.bigdata.model.FaultKeyExtend;
import com.nwpu.bigdata.model.User;
import com.nwpu.bigdata.service.ESLogService;
import com.nwpu.bigdata.service.FaultLogKeyService;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.elasticsearch.common.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时收集错误日志信息，同时存储在mysql数据库中
 *
 * @author chengar zhanggr
 */
@Component
public class LogQuartzJob {

    private static Logger logger = LoggerFactory.getLogger(LogQuartzJob.class);

    private final ESLogService esLogService;

    private final FaultLogKeyService faultLogKeyService;


    @Autowired
    public LogQuartzJob(ESLogService esLogService, FaultLogKeyService faultLogKeyService) {
        this.esLogService = esLogService;
        this.faultLogKeyService = faultLogKeyService;
    }


    public void doLogTask() {
        BackendResult<List<FaultKeyExtend>> backendResult = faultLogKeyService.getFaultKeyExtend();
        List<FaultKeyExtend> faultKeyExtends = backendResult.getData();

        if (faultKeyExtends != null && faultKeyExtends.size() != 0) {
            for (FaultKeyExtend faultKeyExtend : faultKeyExtends) {
                writeLog(faultKeyExtend);
            }
        } else {
            FaultKeyExtend faultKeyExtend = new FaultKeyExtend();
            faultKeyExtend.setKeyword("error,except");
            faultKeyExtend.setUserId(1L);
            faultKeyExtend.setUser(new User());
            faultKeyExtend.getUser().setUsername("admin");
            writeLog(faultKeyExtend);
        }
    }

    private void writeLog(FaultKeyExtend faultKeyExtend) {
        boolean writeStatus = false;
        try {
            writeStatus = esLogService.writeLogToDB("logstash-*", "fluentd",
                    faultKeyExtend, Strings.EMPTY_ARRAY, Strings.EMPTY_ARRAY);
        } catch (NoLogExcetion e) {
            logger.info("No Exception Log info In ElasticSearch!");
        }

        if (writeStatus) {
            logger.info("The exception log info writed successfully !");
        }
    }

}
